package cn.edu.suda.ada.database.connection.pool;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;

import cn.edu.suda.ada.common.config.Config;
import cn.edu.suda.ada.database.exception.DatabaseException;

public class DbcpConnectionPool extends DefaultConnectionPool {
	/**
	 * 数据库连接池
	 */
	private BasicDataSource dataSource;
	
	public DbcpConnectionPool() {
		dataSource = new BasicDataSource();
	}
	
	@Override
	public void init(Config config) throws DatabaseException {
		String url = config.getString("jdbc.url");
		String database = config.getString("jdbc.database");
		if (url.isEmpty()) {
			String link = config.getString("jdbc.link");
			String param = config.getString("jdbc.param");
			url = link + database + param;
		}
		
		dataSource.setDriverClassName(config.getString("jdbc.driver"));
		dataSource.setUrl(url);
		dataSource.setUsername(config.getString("jdbc.username"));
		dataSource.setPassword(config.getString("jdbc.password"));
		
		dataSource.setMaxTotal(config.getInteger("dbcp.maxTotal"));
		dataSource.setInitialSize(config.getInteger("dbcp.initialSize"));
		dataSource.setMaxIdle(config.getInteger("dbcp.maxIdle"));
		dataSource.setMinIdle(config.getInteger("dbcp.minIdle"));
		dataSource.setMaxWaitMillis(config.getLong("dbcp.maxWait"));
		dataSource.setLogAbandoned(config.getBoolean("dbcp.logAbandoned"));
		dataSource.setRemoveAbandonedOnBorrow(config.getBoolean("dbcp.removeAbandonedOnBorrow"));
		dataSource.setRemoveAbandonedTimeout(config.getInteger("dbcp.removeAbandonedTimeout"));
		// TODO 支持所有配置参数
	}
	
	@Override
	public Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}

}
